package com.landcode.land.data.canal.starter;

import com.landcode.land.data.canal.manager.AbstractCanalManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Slf4j
@Component
public class CanalServerStarter implements CommandLineRunner {
    @Autowired
    private AbstractCanalManager canalManager;
    private Thread thread;

    protected Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            log.error("canal parse events has an error", e);
        }
    };

    @Override
    public void run(String... args) throws Exception {
        Assert.notNull(canalManager.getCanalConnector(), "canal connector is null");
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                canalManager.process();
            }
        });
        thread.setUncaughtExceptionHandler(handler);
        thread.start();
    }
}
